﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.DataAccess.SQLDom
{
    class InsertSqlStaPostgreSQL: InsertSqlStatement
    {
        #region 构造函数

        public InsertSqlStaPostgreSQL()
            : base()
        {
        }

        #endregion

        #region 方法

        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns>Insert插入语句</returns>
        public override object Clone()
        {
            var sql = base.Clone() as InsertSqlStaPostgreSQL;
            if (InsertFields != null)
                sql.InsertFields = InsertFields.Clone() as InsertFieldList;
            if (InsertValues != null)
                sql.InsertValues = InsertValues.Clone() as InsertValueList;

            return sql;
        }

        /// <summary>
        /// 转换成SQL
        /// </summary>
        /// <returns>SQL</returns>
        public override string ToSQL()
        {
            string insertSQL = string.Empty;

            var tableName = this.TableName;
            tableName = this.SqlBuildingInfo.WrapByCurrentDBEscapeCharacter(tableName);
            if (string.IsNullOrWhiteSpace(insertSQL))
            {
                //注册用DB转义符包裹列名的方法
                InsertFields.FieldNameWraps = this.SqlBuildingInfo.WrapByCurrentDBEscapeCharacter;
                string insertFieldsSQL = InsertFields.ToSQL(); //.Replace("\"", "");  不加试试
                insertSQL = string.Format("INSERT INTO {0} {1}", tableName, insertFieldsSQL);

                for (int i = 0; i < InsertFields.ChildCollection.Count; i++)
                {
                    InsertValue val = null;
                    if (InsertValues.ChildCollection.Count > 0) //insertValue数量为0代表调试模式
                        val = InsertValues.ChildCollection[i] as InsertValue;
                    var field = InsertFields.ChildCollection[i] as InsertField;
                    //处理不做变量替换的值，直接替换到insert语句中
                    if (!field.IsUseVarBinding)
                    {
                        insertSQL = insertSQL.Replace($":{field.FieldName}", val.Value.ToString());
                    }
                }
            }

            return insertSQL;
        }
        #endregion
    }
}
